package gupao.concurrency.utils;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Utils {
    public static void sleepIgnoreExp(long millis){
        try {
            TimeUnit.MILLISECONDS.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void waitMillis(long millis) {
        long start = System.currentTimeMillis();
        long end;
        long x = 0;
        long total = 1000 * 1000;
        do {
            if(x < total){
                x++;
            }
            end = System.currentTimeMillis();
        } while (start + millis >= end);
    }

    public static void warmUpThreads(ThreadPoolExecutor executor,
                                     ConcurrentHashMap<Long,String> threadIdNameMap,
                                     int concurrency){
        System.out.println("warm up thread pool");
        List<Future<?>> fsList = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(concurrency);
        for(int i = 0; i < concurrency; i++){
            fsList.add(executor.submit(() -> {
                threadIdNameMap.put(Thread.currentThread().getId(), Thread.currentThread().getName());
                latch.countDown();
            }));
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadIdNameMap.forEach((key, val) -> System.out.println(key + " -> " + val));
    }
}
